<template>
  <el-dropdown
    teleported
    popper-class="lang-content"
  >
    <div class="lang-item">
      <img :src="currentIcon">
      <div>{{ $t(currentLang) }}</div>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="item in langItems"
          :key="item.title"
          @click="changeLanguage(item)"
        >
          <img :src="item.icon">
          <span>{{ $t(item.title) }}</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import {defineComponent, ref} from "vue";
import { useI18n } from 'vue-i18n';
import {USER_LANG_ICON,USER_LANG_TITLE,USER_LANG_LOCAL_KEY} from "@/constant.js";
import zhImg from '@/assets/images/ui/lang/chinese.png'
import enImg from '@/assets/images/ui/lang/english.png'

const {locale} = useI18n({
  inheritLocale: true, // 如果你希望从全局配置继承 locale
  useScope: 'global'   // 使用全局的 i18n 实例
})

defineComponent({
  name: 'LangItem'
})

const props = defineProps({
  langItems: {
    type: Array,
    default: ()=>[
      {icon: enImg,title: 'lang.english',localKey: 'en'},
      {icon: zhImg,title: 'lang.chinese',localKey: 'zh'},
    ],
  }
})
const currentIcon =  ref();
const currentLang = ref('lang.chinese');
const emits = defineEmits(['changeLanguage']);
const changeLanguage = (item)=>{
  locale.value = item.localKey;
  currentLang.value = item.title;
  currentIcon.value = item.icon;
  localStorage.setItem(USER_LANG_ICON,item.icon);
  localStorage.setItem(USER_LANG_TITLE,item.title);
  localStorage.setItem(USER_LANG_LOCAL_KEY,item.localKey)
  emits('changeLanguage',item);
};
/**
 * 默认为用户的上次选择，如果没有，则跟随用户的浏览器使用的语言
 */
const restoreLang = ()=>{
  let userLangLocalKey = localStorage.getItem(USER_LANG_LOCAL_KEY);

  if(userLangLocalKey){
    currentLang.value = localStorage.getItem(USER_LANG_TITLE);
    currentIcon.value = localStorage.getItem(USER_LANG_ICON);
    locale.value = userLangLocalKey;
  }else{
    const userLanguage = navigator.language.split('-')[0];
    for(let i=0;i<props.langItems.length;++i){
      let langItem = props.langItems[i];
      if(langItem.localKey===userLanguage){
        changeLanguage(langItem);
        break;
      }
    }
  }
}
  restoreLang();
</script>

<style scoped lang="scss">
.lang-item {
  display: flex;
  flex-direction: row;
  align-items: center;

  &:focus {
    outline:none !important;
  }

  img {
    width: 32px;
    height: 32px;
    cursor: pointer;
    margin-right: 15px;
  }
}
.lang-content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;

  img {
    width: 32px;
    height: 32px;
    cursor: pointer;

    &:focus{
      outline:none !important;
    }
  }
}
</style>